#include "GateServer.h"
#include "GateHandler.h"
#include "JME_JsonFile.h"
#include "JME_Core.h"
#include "DispatchHandler.h"

GateServer::GateServer()
{
}

GateServer::~GateServer()
{

}


GateServer::GateServerPtr GateServer::getInstance()
{
	static GateServerPtr _pInstance = GateServerPtr(new GateServer);
	return _pInstance;
}

// GateServer::GateServerPtr GateServer::create()
// {
// 	return GateServerPtr(new GateServer);
// }

void GateServer::init()
{
	_clientHandler = boost::shared_ptr<GateNetHandler>(new GateNetHandler);

	DispatchHandler::init();

	_config = JMEngine::file::load_jsonfile_val("./config/conf.json");
	auto& _baseConf = _config["base"];

	_serverId = _baseConf["server_id"].asInt();

	auto& rpc = _config["rpc"];
	auto& clientConf = rpc["client"];
	for (auto& c : clientConf)
	{
		auto r = JME_RpcClient::create(c["ip"].asString(), c["port"].asString(), c["reconnect"].asUInt(), c["buffer_size"].asUInt());
		_rpcClient[c["name"].asString()] = r;
	}

	unsigned short port = _config["base"]["port"].asUInt();
	_acceptorPtr = JMEngine::net::JME_TcpAcceptor::create(_clientHandler, port);

	size_t clientBufferSize = _config["base"]["client_buffer_size"].asUInt();
	_acceptorPtr->accept(0, clientBufferSize);

	LogT << "Start accept client connect on port {" << port << "}" << LogEnd;
}

JME_RpcClient::JME_RpcClientPtr GateServer::getRpcByName( const char* name )
{
	auto it = _rpcClient.find(name);

	return it != _rpcClient.end() ? it->second : JME_RpcClientPtr();
}



